
<template>
  <el-dialog
      v-model="dialogVisible"
      title="发起群聊"
      width="800px"
      :before-close="handleClose"
  >
    <div class="create-group-dialog">
      <!-- 群聊名称 -->
      <div class="form-item">
        <label class="form-label">群聊名称</label>
        <el-input
            v-model="groupTitle"
            placeholder="请输入群聊名称"
            maxlength="50"
            show-word-limit
        />
      </div>

      <!-- 成员选择 -->
      <div class="form-item">
        <div class="form-header">
          <label class="form-label">选择成员</label>
          <div class="selected-count">已选择 {{ selectedUsers.length }} 人</div>
        </div>

        <!-- 搜索框 -->
        <div class="search-section">
          <el-input
              v-model="searchMemberText"
              placeholder="搜索联系人"
              prefix-icon="Search"
              clearable
              @input="handleSearchMember"
          />
        </div>

        <!-- 联系人列表 -->
        <div class="contact-selector">
          <div class="selector-header">
            <el-checkbox
                v-model="selectAll"
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
            >
              全选
            </el-checkbox>
            <span class="total-count">共 {{ filteredContacts.length }} 人</span>
          </div>

          <!-- 年级-班级结构 -->
          <div class="contact-hierarchy">
            <!-- 所有老师 -->
            <div class="contact-section">
              <div class="section-header" @click="toggleTeacherSection">
                <el-icon :class="['collapse-icon', { 'is-collapsed': !teacherSectionExpanded }]">
                  <ArrowRight />
                </el-icon>
                <span class="section-title">所有老师</span>
              </div>

              <el-collapse-transition>
                <div v-show="teacherSectionExpanded" class="section-content">
                  <div v-if="teachers.length > 0">
                    <div
                        v-for="teacher in getFilteredTeachers()"
                        :key="teacher.id"
                        class="contact-select-item"
                        @click="toggleContactSelection(teacher)"
                    >
                      <el-checkbox
                          :model-value="isContactSelected(teacher)"
                          @click.stop
                          @change="toggleContactSelection(teacher)"
                      />
                      <el-avatar :size="32" :src="teacher.avatar" class="contact-avatar">
                        {{ teacher.name?.charAt(0) }}
                      </el-avatar>
                      <div class="contact-info">
                        <div class="contact-name">{{ teacher.name }}</div>
                        <div class="contact-role">老师</div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="empty-list">
                    <el-button
                        type="primary"
                        link
                        @click.stop="loadTeachers"
                    >
                      点击加载老师列表
                    </el-button>
                  </div>
                </div>
              </el-collapse-transition>
            </div>

            <!-- 学生列表（按年级班级结构） -->
            <div class="contact-section">
              <div class="section-header" @click="toggleStudentSection">
                <el-icon :class="['collapse-icon', { 'is-collapsed': !studentSectionExpanded }]">
                  <ArrowRight />
                </el-icon>
                <span class="section-title">所有学生</span>
              </div>

              <el-collapse-transition>
                <div v-show="studentSectionExpanded" class="section-content">
                  <!-- 年级列表 -->
                  <div class="grade-list">
                    <div
                        v-for="grade in grades"
                        :key="grade.gradeId"
                        class="grade-item"
                    >
                      <div class="item-header" @click.stop="toggleGrade(grade)">
                        <el-icon :class="['collapse-icon', { 'is-collapsed': !expandedGrades[grade.gradeId] }]">
                          <ArrowRight />
                        </el-icon>
                        <span class="item-title">{{ grade.gradeName }}</span>
                      </div>

                      <el-collapse-transition>
                        <div v-show="expandedGrades[grade.gradeId]" class="item-content">
                          <!-- 班级列表 -->
                          <div class="class-list">
                            <div
                                v-for="classItem in getClassesByGrade(grade.gradeId)"
                                :key="classItem.classId"
                                class="class-item"
                            >
                              <div class="item-header" @click.stop="toggleClass(classItem)">
                                <el-icon :class="['collapse-icon', { 'is-collapsed': !expandedClasses[classItem.classId] }]">
                                  <ArrowRight />
                                </el-icon>
                                <span class="item-title">{{ classItem.className }}</span>
                              </div>

                              <el-collapse-transition>
                                <div v-show="expandedClasses[classItem.classId]" class="item-content">
                                  <!-- 学生列表 -->
                                  <div v-if="getStudentsByClass(classItem.classId).length > 0">
                                    <div
                                        v-for="student in getFilteredStudentsByClass(classItem.classId)"
                                        :key="student.id"
                                        class="contact-select-item"
                                        @click="toggleContactSelection(student)"
                                    >
                                      <el-checkbox
                                          :model-value="isContactSelected(student)"
                                          @click.stop
                                          @change="toggleContactSelection(student)"
                                      />
                                      <el-avatar :size="32" :src="student.avatar" class="contact-avatar">
                                        {{ student.name?.charAt(0) }}
                                      </el-avatar>
                                      <div class="contact-info">
                                        <div class="contact-name">{{ student.name }}</div>
                                        <div class="contact-role">学生</div>
                                      </div>
                                    </div>
                                  </div>

                                  <!-- 加载状态 -->
                                  <div v-else-if="loadingStudents[classItem.classId]" class="loading-list">
                                    <el-icon class="loading-icon"><Loading /></el-icon>
                                    <span>加载中...</span>
                                  </div>

                                  <!-- 加载按钮 -->
                                  <div v-else class="empty-list">
                                    <el-button
                                        type="primary"
                                        link
                                        @click.stop="loadStudentsByClass(classItem.classId)"
                                    >
                                      点击加载学生列表
                                    </el-button>
                                  </div>
                                </div>
                              </el-collapse-transition>
                            </div>
                          </div>

                          <div v-if="getClassesByGrade(grade.gradeId).length === 0" class="empty-list">
                            该年级暂无班级
                          </div>
                        </div>
                      </el-collapse-transition>
                    </div>
                  </div>
                </div>
              </el-collapse-transition>
            </div>
          </div>
        </div>
      </div>

      <!-- 已选成员预览 -->
      <div v-if="selectedUsers.length > 0" class="selected-preview">
        <label class="form-label">已选成员</label>
        <div class="selected-users">
          <el-tag
              v-for="user in selectedUsers"
              :key="user.id"
              closable
              @close="removeSelectedUser(user)"
              class="user-tag"
          >
            {{ user.name }} ({{ getRoleText(user.role) }})
          </el-tag>
        </div>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            type="primary"
            @click="handleCreateGroup"
            :disabled="!canCreateGroup"
            :loading="creatingGroup"
        >
          创建群聊
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, ArrowRight, Loading } from '@element-plus/icons-vue'
import {
  createGroupConversation,
  fetchAllTeachers,
  fetchUserOptions,
  fetchClassesWithGrades,
  fetchGradeList
} from '@/api/teacher'

interface Contact {
  id: number
  name: string
  avatar?: string
  role: string
  type: 'teacher' | 'student'
}

interface Grade {
  gradeId: number
  gradeName: string
}

interface Class {
  classId: number
  className: string
  gradeId: number
}

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'group-created', group: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const groupTitle = ref('')
const searchMemberText = ref('')
const selectedUsers = ref<Contact[]>([])
const selectAll = ref(false)
const isIndeterminate = ref(false)
const creatingGroup = ref(false)

// 联系人数据
const teachers = ref<Contact[]>([])
const students = ref<Contact[]>([])
const grades = ref<Grade[]>([])
const classes = ref<Class[]>([])

// 展开/收起状态
const teacherSectionExpanded = ref(true)
const studentSectionExpanded = ref(true)
const expandedGrades = reactive<Record<number, boolean>>({})
const expandedClasses = reactive<Record<number, boolean>>({})

// 加载状态
const loadingTeachers = ref(false)
const loadingStudents = reactive<Record<number, boolean>>({})

// 计算属性
const allContacts = computed(() => {
  return [...teachers.value, ...students.value]
})

const filteredContacts = computed(() => {
  if (!searchMemberText.value.trim()) {
    return allContacts.value
  }

  const searchText = searchMemberText.value.toLowerCase()
  return allContacts.value.filter(contact =>
      contact.name.toLowerCase().includes(searchText)
  )
})

const canCreateGroup = computed(() => {
  return groupTitle.value.trim().length > 0 && selectedUsers.value.length > 0
})

// 监听选择状态变化
watch(selectedUsers, (newSelected) => {
  const total = filteredContacts.value.length
  const selectedCount = newSelected.length

  if (selectedCount === 0) {
    selectAll.value = false
    isIndeterminate.value = false
  } else if (selectedCount === total) {
    selectAll.value = true
    isIndeterminate.value = false
  } else {
    selectAll.value = false
    isIndeterminate.value = true
  }
}, { deep: true })

// 方法
const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  groupTitle.value = ''
  searchMemberText.value = ''
  selectedUsers.value = []
  selectAll.value = false
  isIndeterminate.value = false

  // 重置展开状态
  teacherSectionExpanded.value = true
  studentSectionExpanded.value = true
  Object.keys(expandedGrades).forEach(key => {
    expandedGrades[parseInt(key)] = false
  })
  Object.keys(expandedClasses).forEach(key => {
    expandedClasses[parseInt(key)] = false
  })
}

const handleSearchMember = () => {
  // 搜索逻辑已在计算属性中处理
}

const isContactSelected = (contact: Contact) => {
  return selectedUsers.value.some(user => user.id === contact.id)
}

const toggleContactSelection = (contact: Contact) => {
  const index = selectedUsers.value.findIndex(user => user.id === contact.id)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
  } else {
    selectedUsers.value.push(contact)
  }
}

const handleSelectAll = (value: boolean) => {
  if (value) {
    selectedUsers.value = [...filteredContacts.value]
  } else {
    selectedUsers.value = []
  }
}

const removeSelectedUser = (user: Contact) => {
  const index = selectedUsers.value.findIndex(u => u.id === user.id)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
  }
}

const getRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    'student': '学生',
    'teacher': '老师',
    'admin': '管理员'
  }
  return roleMap[role] || '用户'
}

// 展开/收起控制
const toggleTeacherSection = () => {
  teacherSectionExpanded.value = !teacherSectionExpanded.value
  if (teacherSectionExpanded.value && teachers.value.length === 0) {
    loadTeachers()
  }
}

const toggleStudentSection = () => {
  studentSectionExpanded.value = !studentSectionExpanded.value
}

const toggleGrade = (grade: Grade) => {
  const gradeId = grade.gradeId
  expandedGrades[gradeId] = !expandedGrades[gradeId]
}

const toggleClass = (classItem: Class) => {
  const classId = classItem.classId
  expandedClasses[classId] = !expandedClasses[classId]
  if (expandedClasses[classId] && getStudentsByClass(classId).length === 0) {
    loadStudentsByClass(classId)
  }
}

// 过滤方法
const getFilteredTeachers = () => {
  if (!searchMemberText.value.trim()) {
    return teachers.value
  }
  const searchText = searchMemberText.value.toLowerCase()
  return teachers.value.filter(teacher =>
      teacher.name.toLowerCase().includes(searchText)
  )
}

const getFilteredStudentsByClass = (classId: number) => {
  const classStudents = getStudentsByClass(classId)
  if (!searchMemberText.value.trim()) {
    return classStudents
  }
  const searchText = searchMemberText.value.toLowerCase()
  return classStudents.filter(student =>
      student.name.toLowerCase().includes(searchText)
  )
}

// 数据加载方法
const loadTeachers = async () => {
  try {
    loadingTeachers.value = true
    const response = await fetchAllTeachers()
    if (response.success) {
      teachers.value = (response.data || []).map((teacher: any) => ({
        id: teacher.id,
        name: teacher.name,
        avatar: teacher.avatar,
        role: 'teacher',
        type: 'teacher'
      }))
    }
  } catch (error) {
    console.error('加载老师数据失败:', error)
    ElMessage.error('加载老师数据失败')
  } finally {
    loadingTeachers.value = false
  }
}

const loadStudentsByClass = async (classId: number) => {
  try {
    loadingStudents[classId] = true
    const response = await fetchUserOptions('', 'student', classId)
    if (response.success) {
      const classStudents = response.data || []
      // 移除该班级的旧学生数据
      students.value = students.value.filter(s => !s.classId || s.classId !== classId)
      // 添加新学生数据
      students.value.push(...classStudents.map((student: any) => ({
        id: student.id,
        name: student.name,
        avatar: student.avatar,
        role: 'student',
        type: 'student',
        classId: classId
      })))
    }
  } catch (error) {
    console.error(`加载班级 ${classId} 的学生数据失败:`, error)
    ElMessage.error('加载学生数据失败')
  } finally {
    loadingStudents[classId] = false
  }
}

const loadInitialData = async () => {
  try {
    // 加载年级数据
    const gradesResponse = await fetchGradeList()
    if (gradesResponse.success) {
      grades.value = gradesResponse.data.map((gradeName: string, index: number) => ({
        gradeId: index + 1,
        gradeName: gradeName
      }))
    }

    // 加载班级数据
    const classesResponse = await fetchClassesWithGrades()
    if (classesResponse.success) {
      classes.value = classesResponse.data.map((classItem: any) => ({
        classId: classItem.classId,
        className: classItem.className,
        gradeId: classItem.gradeId || extractGradeIdFromDisplayName(classItem.displayName)
      }))
    }
  } catch (error) {
    console.error('加载年级班级数据失败:', error)
    ElMessage.error('加载年级班级数据失败')
  }
}

const extractGradeIdFromDisplayName = (displayName: string): number => {
  const gradeMap: Record<string, number> = {
    '一年级': 1, '二年级': 2, '三年级': 3,
    '四年级': 4, '五年级': 5, '六年级': 6
  }
  for (const [gradeName, gradeId] of Object.entries(gradeMap)) {
    if (displayName?.includes(gradeName)) {
      return gradeId
    }
  }
  return 0
}

const getClassesByGrade = (gradeId: number): Class[] => {
  return classes.value.filter(c => c.gradeId === gradeId)
}

const getStudentsByClass = (classId: number): Contact[] => {
  return students.value.filter(s => s.classId === classId)
}

// 创建群聊
const handleCreateGroup = async () => {
  if (!canCreateGroup.value) return

  try {
    creatingGroup.value = true

    const requestData = {
      title: groupTitle.value.trim(),
      participantIds: selectedUsers.value.map(user => user.id)
    }

    const response = await createGroupConversation(requestData)

    if (response.success) {
      ElMessage.success('群聊创建成功')
      emit('group-created', response.data)
      handleClose()
    } else {
      ElMessage.error(response.message || '创建群聊失败')
    }
  } catch (error) {
    console.error('创建群聊失败:', error)
    ElMessage.error('创建群聊失败')
  } finally {
    creatingGroup.value = false
  }
}

// 生命周期
onMounted(() => {
  loadInitialData()
})

// 监听对话框显示状态，每次打开时重新加载数据
watch(() => props.visible, (newValue) => {
  if (newValue) {
    loadInitialData()
    if (teacherSectionExpanded.value && teachers.value.length === 0) {
      loadTeachers()
    }
  } else {
    resetForm()
  }
})
</script>

<style scoped>
.create-group-dialog {
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 24px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #303133;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.selected-count {
  font-size: 12px;
  color: #909399;
}

.search-section {
  margin-bottom: 16px;
}

.contact-selector {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  max-height: 400px;
  overflow-y: auto;
}

.selector-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.total-count {
  font-size: 12px;
  color: #909399;
}

.contact-hierarchy {
  padding: 8px;
}

.contact-section {
  margin-bottom: 8px;
}

.section-header {
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  user-select: none;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.section-header:hover {
  background-color: #f5f7fa;
}

.section-title {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.section-content {
  padding-left: 16px;
}

.collapse-icon {
  margin-right: 8px;
  transition: transform 0.3s;
}

.collapse-icon.is-collapsed {
  transform: rotate(90deg);
}

.grade-item,
.class-item {
  margin: 4px 0;
}

.item-header {
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.item-header:hover {
  background-color: #f5f7fa;
}

.item-title {
  font-size: 13px;
  color: #606266;
}

.item-content {
  padding-left: 20px;
}

.contact-select-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin: 2px 0;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.contact-select-item:hover {
  background-color: #f5f7fa;
}

.contact-avatar {
  margin: 0 12px;
  flex-shrink: 0;
}

.contact-info {
  flex: 1;
  min-width: 0;
}

.contact-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
}

.contact-role {
  font-size: 12px;
  color: #909399;
}

.selected-preview {
  margin-top: 16px;
}

.selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.user-tag {
  max-width: 150px;
}

.empty-list {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 13px;
}

.loading-list {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.loading-icon {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 滚动条样式 */
.contact-selector::-webkit-scrollbar {
  width: 6px;
}

.contact-selector::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.contact-selector::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.contact-selector::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
